﻿using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using net.xBei.WebApi.Repository;

namespace net.xBei.WebApi.Filters {
    /// <summary>
    /// API执行时间计时器
    /// </summary>
    public class ApiTimerFilter(EventService eventService) : IActionFilter {
        /// <summary>
        /// 事件类型
        /// </summary>
        public const string EventKey = "ApiLogger";
        private readonly Stopwatch Timmer = new();
        private DateTime begin;

        /// <inheritdoc/>
        public void OnActionExecuted(ActionExecutedContext context) {
            Timmer.Stop();
            //Order.API.Controllers.FbaController.GetOrderList (Order.API)
            var action = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
            _ = eventService.FireAsync(EventKey, new EventData {
                Service = ApiTimerFilter.GetService(action.DisplayName?.Trim()),
                Controller = action.ControllerName,
                Action = action.ActionName,
                DisplayName = action.DisplayName,
                Route = action.AttributeRouteInfo?.Template ?? string.Empty,
                Start = begin,
                Elapsed = Timmer.Elapsed,
            });
        }

        private static string GetService(string? str) {
            if (string.IsNullOrWhiteSpace(str)) return string.Empty;
            var i = str.IndexOf('(');
            if (i > 0) {
                str = str[(i + 1)..];
                return str[..^1];
            }
            return str;
        }
        /// <inheritdoc/>
        public void OnActionExecuting(ActionExecutingContext context) {
            begin = DateTime.UtcNow;
            Timmer.Start();
            //Console.WriteLine(context.ActionArguments.ToJson(true));
        }

#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
        public struct EventData {
            public string Service;
            public string Controller;
            public string Action;
            public string? DisplayName;
            public string Route;
            public DateTime Start;
            public TimeSpan Elapsed;
        }
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
    }
}
